package com.livegoods.service.impl;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.pojo.Comment;
import com.livegoods.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据房屋的id查询评论
    @Override
    public LivegoodsResult findCommentByHouseId(String id,int page,int size) {


        try {
            Criteria criteria = Criteria.where("houseId").is(id);

            Query query = new Query(criteria);

            query.with(PageRequest.of(page,size, Sort.by(Sort.Order.desc("star"))));

            List<Comment> comments = mongoTemplate.find(query, Comment.class);

            // 手机号中间四位变成****
            for (Comment comment: comments) {
                // $1 表示取出第一个()里面内容
                String phoneNumber = comment.getUsername().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                comment.setUsername(phoneNumber);
            }

            //使用聚合查询查询所有总数
            GroupOperation groupOperation = Aggregation.group().count().as("total");


            TypedAggregation<Comment> commentTypedAggregation = new TypedAggregation<>(Comment.class,groupOperation);

            AggregationResults<Map> aggregate = mongoTemplate.aggregate(commentTypedAggregation, Map.class);

            Map uniqueMappedResult = aggregate.getUniqueMappedResult();


            LivegoodsResult ok = LivegoodsResult.ok(comments);

            //获取总数
            int total = (int)uniqueMappedResult.get("total");

            //计算总页数
            int totalPage = total % size == 0 ? total/size : total/size +1;


            if((page+1)<totalPage){
                ok.setHasMore(true);
            }

            ok.setTotalPage(totalPage);

            return ok;
        } catch (Exception e) {
            return LivegoodsResult.error("查询评论失败....");
        }
    }
}
